/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 * 
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

/*
 * This file is a skeleton for developing Ethernet network interface
 * drivers for lwIP. Add code to the low_level functions and do a
 * search-and-replace for the word "ethernetif" to replace it with
 * something that better describes your network interface.
 */
#include <string.h>
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include <lwip/stats.h>
#include <lwip/snmp.h>
#include "netif/etharp.h"
#include "netif/ppp/pppoe.h"


extern void Eth_AutoNegotiation_Det(void);

/**
 * Stm32f20x DriverLib Header Files required for this interface driver.
 */
#include "netif/ethernetif.h"
#include "stm32f2x7_eth.h"

/*****************************************************************************
 *
 ****************************************************************************/
/* Define those to better describe your network interface. */
#define IFNAME0 's'
#define IFNAME1 't'

                       
                        
/*define MAC address*/
#define MAC_ADDR0   0x2c
#define MAC_ADDR1   0x6f
#define MAC_ADDR2   0x65
#define MAC_ADDR3   0x62
#define MAC_ADDR4   0xec
#define MAC_ADDR5   0xeb

#define ETHERNETIF_INPUT_TASK_STACK_SIZE     128
#define ETHERNETIF_INPUT_TASK_PRIORITY       2
#define ETHERNETIF_INPUT_BLOCK_TIME          100    /*ms*/
#define ETHERNETIF_INPUT_BLOCK_TIME_TOTAL    5000   /*ms*/
   
   

//#define ETHERNETIF_TX_MUTEX

/**
 * Helper struct to hold private data used to operate your ethernet interface.
 * Keeping the ethernet address of the MAC in this struct is not necessary
 * as it is already kept in the struct netif.
 * But this is only an example, anyway...
 */
struct ethernetif {
  struct eth_addr *ethaddr;
  /* Add whatever per-interface state that is needed here. */
  sys_sem_t   rx_sem;

  #ifdef ETHERNETIF_TX_MUTEX
  sys_mutex_t tx_mutex;
  #endif
};

static struct ethernetif  EthernetIf;

/*****************************************************************************
 *
 ****************************************************************************/

/* Ethernet Rx & Tx DMA Descriptors */
extern ETH_DMADESCTypeDef  DMARxDscrTab[ETH_RXBUFNB];
extern ETH_DMADESCTypeDef  DMATxDscrTab[ETH_TXBUFNB];

/* Ethernet Receive && Transmit buffers  */
extern uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE];
extern uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE];

/* Global pointers to track current transmit and receive descriptors */
extern ETH_DMADESCTypeDef  *DMARxDescToGet;
extern ETH_DMADESCTypeDef  *DMATxDescToSet;

/* Global pointer for last received frame infos */
extern ETH_DMA_Rx_Frame_infos *DMA_RX_FRAME_infos;

/*****************************************************************************
 *  Forward declarations.
 ****************************************************************************/
static void ethernetif_input(void *arg);

/*****************************************************************************
Function      : low_level_init
Description   : In this function, the hardware should be initialized.
                Called from ethernetif_init().
Input         : @param netif the already initialized lwip network interface structure
                for this ethernetif
Output        :
Return        :
Others        :
*****************************************************************************/
static void low_level_init(struct netif *netif)
{
  struct ethernetif *ethernetif = netif->state;
  int i;
  
  /* set MAC hardware address length */
  netif->hwaddr_len = ETHARP_HWADDR_LEN;

  /* set MAC hardware address */
  /*netif->hwaddr[0] = MAC_ADDR0;
  netif->hwaddr[1] = MAC_ADDR1;
  netif->hwaddr[2] = MAC_ADDR2;
  netif->hwaddr[3] = MAC_ADDR3;
  netif->hwaddr[4] = MAC_ADDR4;
  netif->hwaddr[5] = MAC_ADDR5;*/

  /* maximum transfer unit */
  netif->mtu = 1500;
  
  /* device capabilities */
  /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
  netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
 
  /* Do whatever else is needed to initialize interface. */
  /* Disable all Ethernet Interrupts. */

  /* create binary semaphore used for informing ethernetif of frame reception */
  if (sys_sem_new(&ethernetif->rx_sem, 0) != ERR_OK) {
    ethernetif->rx_sem = 0;
  }

  /* create binary semaphore used for informing ethernetif of frame transmission */
  #ifdef ETHERNETIF_TX_MUTEX
  if (sys_mutex_new(&ethernetif->tx_mutex) != ERR_OK) {
    ethernetif->tx_mutex = 0;
  }
  #endif


  /* initialize MAC address in ethernet MAC */
  ETH_MACAddressConfig(ETH_MAC_Address0, netif->hwaddr);

  /* Initialize Tx Descriptors list: Chain Mode */
  ETH_DMATxDescChainInit(DMATxDscrTab, &Tx_Buff[0][0], ETH_TXBUFNB);
  /* Initialize Rx Descriptors list: Chain Mode  */
  ETH_DMARxDescChainInit(DMARxDscrTab, &Rx_Buff[0][0], ETH_RXBUFNB);

  /* Enable Ethernet Rx interrrupt */
  {
    for(i=0; i<ETH_RXBUFNB; i++) {
      ETH_DMARxDescReceiveITConfig(&DMARxDscrTab[i], ENABLE);
    }
  }

#ifdef CHECKSUM_BY_HARDWARE
  /* Enable the checksum insertion for the Tx frames */
  {
    for(i=0; i<ETH_TXBUFNB; i++) {
      ETH_DMATxDescChecksumInsertionConfig(&DMATxDscrTab[i], ETH_DMATxDesc_ChecksumTCPUDPICMPFull);
    }
  }
#endif

  /* create the task that handles the ETH_MAC */
  sys_thread_new("ethernetif_input",
                 ethernetif_input,
                (void *)netif,
                 ETHERNETIF_INPUT_TASK_STACK_SIZE,
                 ETHERNETIF_INPUT_TASK_PRIORITY);

  /* Enable MAC and DMA transmission and reception */
  ETH_Start();
}

/*****************************************************************************
Function      : low_level_output
Description   : This function should do the actual transmission of the packet.
                The packet is contained in the pbuf that is passed to the function.
                This pbuf might be chained.
Input         : @param netif the lwip network interface structure for this ethernetif
                @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
Output        :
Return        : ERR_OK if the packet could be sent
                an err_t value if the packet couldn't be sent
Others        : @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
                 strange results. You might consider waiting for space in the DMA queue
                 to become availale since the stack doesn't retry to send a packet
                 dropped because of memory failure (except for the TCP timers).
*****************************************************************************/
static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
#ifdef ETHERNETIF_TX_MUTEX  
  struct ethernetif *ethernetif = netif->state;
#endif  
  struct pbuf *q;
  char *buffer;
  u32_t txlen, remain;

#if ETH_PAD_SIZE
  pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif

  txlen = 0;
  for(q = p; q != NULL; q = q->next) {
    txlen += q->len;
  }

  /* Copy transmission frame from stack buffer to ethernet driver buffer */
  if (txlen && txlen <= sizeof(Tx_Buff)) {
    remain = 2;

    #ifdef ETHERNETIF_TX_MUTEX
    sys_mutex_lock(&ethernetif->tx_mutex);
    #endif

//    while (ETH_GetDMATxDescSizeOwnedByCpu(DMATxDescToSet) < txlen) {
//      //not enough space in the DMA queue, wait it
//      #ifdef ETHERNETIF_TX_MUTEX
//      sys_mutex_unlock(&ethernetif->tx_mutex);
//      #endif
//
//      if (remain == 0) {
//        goto output_exit;
//      }
//      remain--;
//      sys_time_delay(50);
//
//      #ifdef ETHERNETIF_TX_MUTEX
//      sys_mutex_lock(&ethernetif->tx_mutex);
//      #endif
//    }
    buffer = (char *)(DMATxDescToSet->Buffer1Addr);
    for(q = p; q != NULL; q = q->next) {
      if (buffer + q->len < (char *)Tx_Buff + sizeof(Tx_Buff)) {
        memcpy(buffer, q->payload, q->len);
        buffer += q->len;
      } else {
        remain = (u32_t)((char *)Tx_Buff + sizeof(Tx_Buff) - buffer);
        memcpy(buffer, q->payload, remain);
        buffer = (char *)Tx_Buff;
        memcpy(buffer, (char *)(q->payload)+remain, q->len-remain);
        buffer += (q->len-remain);
      }
    }

    ETH_Prepare_Transmit_Descriptors(txlen);

    #ifdef ETHERNETIF_TX_MUTEX
    sys_mutex_unlock(&ethernetif->tx_mutex);
    #endif
  }

output_exit:

  #if ETH_PAD_SIZE
  pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
  #endif

  LINK_STATS_INC(link.xmit);

  return ERR_OK;
}

/*****************************************************************************
Function      : low_level_input
Description   : Should allocate a pbuf and transfer the bytes of the incoming
                packet from the interface into the pbuf.
Input         : @param netif the lwip network interface structure for this ethernetif
Output        :
Return        : a pbuf filled with the received packet (including MAC header)
                NULL on memory error
Others        :
*****************************************************************************/
static struct pbuf *low_level_input(struct netif *netif)
{
  struct pbuf *p, *q;
  char *buffer;
  FrameTypeDef frame;
  __IO ETH_DMADESCTypeDef *DMARxNextDesc;
  u16_t len, i;

  p = NULL;

  /* Get received frame */
  frame = ETH_Get_Received_Frame_interrupt();
  if (frame.descriptor == NULL) {
    goto check;
  }
  /* check that frame has no error */
  if ((frame.descriptor->Status & ETH_DMARxDesc_ES) == (uint32_t)RESET) {
    /* Obtain the size of the packet and put it into the "len" variable. */
    buffer = (char *)frame.buffer;
    len = frame.length;

    #if ETH_PAD_SIZE
    len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
    #endif

    /* We allocate a pbuf chain of pbufs from the pool. */
    p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);

    /* Copy received frame from ethernet driver buffer to stack buffer */
    if (p != NULL) {

      #if ETH_PAD_SIZE
      pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
      #endif

      for(q = p; q != NULL; q = q->next) {
        if (buffer + q->len < (char*)Rx_Buff + sizeof(Rx_Buff)) {
          memcpy(q->payload, buffer, q->len);
          buffer += q->len;
        } else {
          i = (u16_t)((char*)Rx_Buff + sizeof(Rx_Buff) - buffer);
          memcpy(q->payload, buffer, i);
          buffer = (char*)Rx_Buff;
          memcpy((char*)q->payload+i, buffer, q->len-i);
          buffer += (q->len-i);
        }
      }

      #if ETH_PAD_SIZE
      pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
      #endif

      LINK_STATS_INC(link.recv);
    } else {
      LINK_STATS_INC(link.memerr);
      LINK_STATS_INC(link.drop);
    }
  }

  /* Release descriptors to DMA */
  /* Check if received frame with multiple DMA buffer segments */
  DMARxNextDesc = DMA_RX_FRAME_infos->FS_Rx_Desc;
  for (i=0; i<DMA_RX_FRAME_infos->Seg_Count; i++) {
    /* Set Own bit in Rx descriptors: gives the buffers back to DMA */
    DMARxNextDesc->Status = ETH_DMARxDesc_OWN;
    DMARxNextDesc = (ETH_DMADESCTypeDef *)(DMARxNextDesc->Buffer2NextDescAddr);
  }
  DMA_RX_FRAME_infos->Seg_Count =0;

check:
  /* When Rx Buffer unavailable flag is set: clear it and resume reception */
  if ((ETH->DMASR & ETH_DMASR_RBUS) != (u32_t)RESET) {
    /* Clear RBUS ETHERNET DMA flag */
    ETH->DMASR = ETH_DMASR_RBUS;
    /* Resume DMA reception */
    ETH->DMARPDR = 0;
  }
  return p;
}

/*****************************************************************************
Function      : ethernetif_input
Description   : This function is the ethernetif_input task, it is processed when a packet
                is ready to be read from the interface. It uses the function low_level_input()
                that should handle the actual reception of bytes from the network
                interface. Then the type of the received packet is determined and
                the appropriate input function is called.
Input         : @param netif the lwip network interface structure for this ethernetif
Output        :
Return        :
Others        :
*****************************************************************************/
static void ethernetif_input(void *arg)
{
  struct netif *netif = (struct netif *)arg;
  struct ethernetif *ethernetif;
  struct eth_hdr *ethhdr;
  struct pbuf *p;
  static unsigned int timeout_times=0;

  ethernetif = netif->state;

  for (;;) {

    /* move received packet into a new pbuf */
    p = low_level_input(netif);
    /* no packet could be read, silently ignore this */
    if (p) {
      /* points to packet payload, which starts with an Ethernet header */
      ethhdr = p->payload;

      switch (htons(ethhdr->type)) {
        /* IP or ARP packet? */
        case ETHTYPE_IP:
        case ETHTYPE_ARP:
        #if PPPOE_SUPPORT
        /* PPPoE packet? */
        case ETHTYPE_PPPOEDISC:
        case ETHTYPE_PPPOE:
        #endif /* PPPOE_SUPPORT */
          /* full packet send to tcpip_thread to process */
          if (netif->input(p, netif)!=ERR_OK) {
             LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
             pbuf_free(p);
             p = NULL;
          }
          break;

        default:
          pbuf_free(p);
          p = NULL;
          break;
      }
      timeout_times = 0;
    } else {
      if (sys_arch_sem_wait(&ethernetif->rx_sem, ETHERNETIF_INPUT_BLOCK_TIME) == SYS_ARCH_TIMEOUT) {
        if(++timeout_times >= ETHERNETIF_INPUT_BLOCK_TIME_TOTAL/ETHERNETIF_INPUT_BLOCK_TIME) {
          timeout_times = 0;
          Eth_AutoNegotiation_Det();
        }
      }
    }
  }
}

/*****************************************************************************
Function      : ethernetif_init
Description   : Should be called at the beginning of the program to set up the
                network interface. It calls the function low_level_init() to do the
                actual setup of the hardware.
Input         : @param netif the lwip network interface structure for this ethernetif
Output        :
Return        : ERR_OK if the loopif is initialized
                ERR_MEM if private data couldn't be allocated any other err_t on error
Others        : This function should be passed as a parameter to netif_add().
*****************************************************************************/
err_t ethernetif_init(struct netif *netif)
{
  struct ethernetif *ethernetif;

  LWIP_ASSERT("netif != NULL", (netif != NULL));
    
  ethernetif = &EthernetIf;

#if LWIP_NETIF_HOSTNAME
  /* Initialize interface hostname */
  netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */

  /*
   * Initialize the snmp variables and counters inside the struct netif.
   * The last argument should be replaced with your link speed, in units
   * of bits per second.
   */
  NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, LINK_SPEED_OF_YOUR_NETIF_IN_BPS);

  netif->state = ethernetif;
  netif->name[0] = IFNAME0;
  netif->name[1] = IFNAME1;
  /* We directly use etharp_output() here to save a function call.
   * You can instead declare your own function an call etharp_output()
   * from it if you have to do some checks before sending (e.g. if link
   * is available...) */
  netif->output = etharp_output;
  netif->linkoutput = low_level_output;
  
  ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]);
  
  /* initialize the hardware */
  low_level_init(netif);

  return ERR_OK;
}

/*****************************************************************************
Function      : ETH_IRQHandler
Description   : This function handles ethernet DMA interrupt request.
Input         :
Output        :
Return        :
Others        :
*****************************************************************************/
void ETH_IRQHandler(void)
{
 
  /* Frame received */
  if ( ETH_GetDMAFlagStatus(ETH_DMA_FLAG_R) == SET) {
    /* Give the semaphore to wakeup LwIP task */
    sys_sem_signal(&EthernetIf.rx_sem);
  }

  /* Clear the interrupt flags. */
  /* Clear the Eth DMA Rx IT pending bits */
  ETH_DMAClearITPendingBit(ETH_DMA_IT_R);
  ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS);
}
